const express = require('axios');
const router = express.Router();
const Product = require('../models/Product');
const Review = require('../models/Review');
const { OpenAI } = require('openai');

const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY
});

// 生成商品描述
router.post('/generate-description', async (req, res) => {
    try {
        const { productId, tone = 'professional' } = req.body;
        
        const product = await Product.findByPk(productId);
        if (!product) {
            return res.status(404).json({ error: '产品未找到' });
        }

        const prompt = `
        为以下产品生成一个SEO优化的商品描述：
        产品名称：${product.name}
        类别：${product.category}
        标签：${product.tags}
        
        要求：
        1. 使用${tone}的语调
        2. 包含相关关键词
        3. 长度150-200字
        4. 突出产品卖点
        5. 适合电商平台使用
        `;

        const completion = await openai.chat.completions.create({
            model: "gpt-3.5-turbo",
            messages: [
                { role: "system", content: "你是一个专业的电商文案撰写师" },
                { role: "user", content: prompt }
            ],
            max_tokens: 300,
            temperature: 0.7
        });

        const description = completion.choices[0].message.content.trim();
        
        // 保存AI生成的描述
        product.ai_description = description;
        await product.save();

        res.json({ description });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 智能定价建议
router.post('/price-suggestion', async (req, res) => {
    try {
        const { productId } = req.body;
        
        const product = await Product.findByPk(productId);
        if (!product) {
            return res.status(404).json({ error: '产品未找到' });
        }

        // 获取同类产品价格
        const similarProducts = await Product.findAll({
            where: {
                category: product.category,
                id: { [Op.ne]: productId }
            },
            attributes: ['price', 'stock_quantity']
        });

        const prices = similarProducts.map(p => parseFloat(p.price));
        const avgPrice = prices.reduce((a, b) => a + b, 0) / prices.length;

        const prompt = `
        基于以下信息提供定价建议：
        当前产品价格：${product.price}
        同类平均价格：${avgPrice.toFixed(2)}
        库存数量：${product.stock_quantity}
        
        请提供：
        1. 建议价格
        2. 定价理由
        3. 价格策略建议
        `;

        const completion = await openai.chat.completions.create({
            model: "gpt-3.5-turbo",
            messages: [
                { role: "system", content: "你是一个电商定价策略专家" },
                { role: "user", content: prompt }
            ],
            max_tokens: 200,
            temperature: 0.5
        });

        const suggestion = completion.choices[0].message.content.trim();
        
        // 提取建议价格
        const priceMatch = suggestion.match(/\d+\.\d{2}/);
        if (priceMatch) {
            product.ai_price_suggestion = parseFloat(priceMatch[0]);
            await product.save();
        }

        res.json({ suggestion, suggestedPrice: product.ai_price_suggestion });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// 分析评论情感
router.post('/analyze-review', async (req, res) => {
    try {
        const { reviewId } = req.body;
        
        const review = await Review.findByPk(reviewId);
        if (!review) {
            return res.status(404).json({ error: '评论未找到' });
        }

        const prompt = `
        分析以下商品评论的情感：
        评分：${review.rating}/5
        评论内容：${review.comment}
        
        请提供：
        1. 情感倾向（positive/negative/neutral）
        2. 情感强度（0-1之间的数值）
        3. 主要情感关键词
        `;

        const completion = await openai.chat.completions.create({
            model: "gpt-3.5-turbo",
            messages: [
                { role: "system", content: "你是一个情感分析专家" },
                { role: "user", content: prompt }
            ],
            max_tokens: 150,
            temperature: 0.3
        });

        const analysis = completion.choices[0].message.content.trim();
        
        // 提取情感标签和分数
        const sentimentLabel = analysis.includes('positive') ? 'positive' : 
                              analysis.includes('negative') ? 'negative' : 'neutral';
        
        const scoreMatch = analysis.match(/\d+\.\d+/);
        const sentimentScore = scoreMatch ? parseFloat(scoreMatch[0]) : 0.5;

        review.sentiment_label = sentimentLabel;
        review.sentiment_score = sentimentScore;
        review.is_analyzed = true;
        await review.save();

        res.json({ 
            analysis, 
            sentimentLabel, 
            sentimentScore 
        });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

module.exports = router;
